var $ = require('jquery');
var util = require('imutil');
var _ = require('underscore');
var Backbone = require('backbone');
var tpl = require('../tpl');
var bus = require('bus');
var chatImgUtil = require('../biz/chatImgUtil');
var wptr = require('wptr');


var Message = require('../model/message');
var Messages = require('../model/messages');

var ChatContentView = require('./chatcontent');
var ChatEnterView = require('./chatenter');
var ImgBoxView = require('./imgbox');
var BlockNoticeView = require('./blocknotice');



module.exports = Backbone.View.extend({
	el: null,
	template:tpl.chat2.chat2,
    events:{
        "click .J-im-btn":"sendMessage",
        "click .J-im-msg-resend":"resendMsg",
        "click .J-im-btn-sendlink":"sendProdMsg"
    },
	initialize: function(options, api, uid,productId){
		var _this = this;
		this.api = api;
		this.uid = uid;
        this.productId = productId;
		this.opt = {
            count:10
        }
		this.api.ready(function(){
			_this.start();
		});
	},
	start: function(){
		var that = this;
		this.api.models.chat2User = this.chat2User = this.api.models.contacts.get(this.uid);
		this.render();

        this.views = {};

        this.views.ChatEnter = new ChatEnterView({
            el: this.$('.J-im-footer'),
            collection: ""
        }, this.api);

        this.views.Imgbox = new ImgBoxView({
            el: this.$('.J-im-footer'),
            collection: ""
        }, this.api);

        this.views.BlockNoticeView = new BlockNoticeView({
            el: this.$('.J-im-block-notice'),
            collection: ""
        }, this.api, this.uid);
		
		var messages;
        this.api.sdk.getUserMessages(this.uid,this.opt,function(result){
            result.messages.sort(function(a,b){
                return a.timestamp- b.timestamp;
            });

            messages = new Messages(result.messages);
            messages.each(function(msg){
                msg.set({explainProd:!msg.get("read")});
            });
            var lastHistoryMsg =messages.length>0?messages.first().toJSON():"";
            that.lastMsgTime = lastHistoryMsg.timestamp;
            that.opt.count = 20;
            that.opt.from = that.lastMsgTime-1;
			that.views.ChatContentView = new ChatContentView({
				el: that.$('.J-im-chat-box'),
				collection: messages
			}, that.api, that.uid,that.productId);

			// 聊天页，当接收到消息后，自动设置为已读
			that.listenTo(bus, 'receiveMessage', function(msg){
				if(that.uid === msg.userId){
                    msg.explainProd = !msg.read;
					//时间戳
                    that.views.ChatContentView.addTimestamp(that.lastMsgTime,msg.timestamp);
					that.views.ChatContentView.addMessage(msg);
                    that.lastMsgTime = msg.timestamp;
                    //标记为已读
                    that.read();
				}
			});

            // 聊天页，当其他客户端接收到消息后
            that.listenTo(bus, 'messageSync', function(msg){
                msg.explainProd = !msg.read;
                //时间戳
                that.views.ChatContentView.addTimestamp(that.lastMsgTime,msg.timestamp);
                that.views.ChatContentView.addMessage(msg);
                that.lastMsgTime = msg.timestamp;
                //标记为已读
                that.read();
            });

            // 进入聊天页，设置所有消息已读
            that.read();

		});
		


        this.listenTo(this.views.Imgbox,'selectImg',function(imgTitle){
            this.views.ChatEnter.addText(imgTitle)
        });
        this.listenTo(this.views.Imgbox,'imgdelete',function(imgTitle){
            this.views.ChatEnter.deleteText(this.views.ChatEnter.elems.$input.val(),this.views.ChatEnter.elems.$input.val().length-1);
        });
        this.listenTo(this.views.ChatEnter,'showKeyBtn',function(){
            this.views.Imgbox.show();
            this.adjustPaddingBottom();
        });
        this.listenTo(this.views.ChatEnter,'showFaceBtn',function(){
            this.views.Imgbox.hide();
            this.adjustPaddingBottom();
        });
        this.listenTo(this.views.ChatEnter,'enterMsg',function(){
            this.sendMessage();
            this.adjustPaddingBottom();
        });
        
        this.listenTo(this.views.ChatEnter, 'resize', function(){
            this.adjustPaddingBottom();
        });

        new wptr({
            contentEl: that.$('.J-im-chat-box'),	// the element(jquery dom) holding pannable content area
            ptrMargin:0,
            distanceToRefresh: 50,	// Number of pixels of panning until refresh
            loadingFunction: function(){
                return new Promise(function(resolve){
                    // Run some async loading code here
                    that.api.sdk.getUserMessages(that.uid,that.opt,function(result){
                        if(result.messages.length>0){
                            result.messages.sort(function(a,b){
                                return b.timestamp- a.timestamp;
                            });
                            var hismsg = new Messages(result.messages);
                            that.opt.from = hismsg.last().toJSON().timestamp-1;
                            that.views.ChatContentView.addHistoryMsg(hismsg);
                        }
                        resolve();
                    });
                });
            },	// Pointer to function that does the loading and returns a promise
            resistance: 5,	// Dragging resistance level
            text:{
                initial:'',//pull to refresh
                loading:'Loading...',//loading...
                nomore:'Life is brief'
            }
        });
        
        // 初始化后默认调整一次
        this.adjustPaddingBottom();
	},
    // 动态调整消息展示框尺寸
    adjustPaddingBottom: function(){
        this.$(".J-im-chat-box").css('paddingBottom', this.$('.J-im-footer').height());
    },
	// 设置当前聊天对象的消息全部已读
	read: function(){
		var _this = this;

		this.api.sdk.readMessagesByUid(this.uid, function(){
			var user = _this.api.models.contacts.get(_this.uid);
			user && user.set({
				unread: 0
			}, {silent: true});
		});
	},
	render: function(){
		this.$el.append(this.template());
	},
    sendMessage:function(){
        this._sendMessage($(".J-im-c-func").val());
        $(".J-im-c-func").val("");
        this.views.ChatEnter.flextext.adjust();
    },
    resendMsg:function(e){
        var resendCid = e.currentTarget.parentElement.getAttribute("msgcid");
        var resendMsg = this.views.ChatContentView.collection.get(resendCid);
        this.views.ChatContentView.collection.remove(resendCid);
        this._sendMessage(resendMsg.toJSON()._msg);
    },
    sendProdMsg:function(){
        this._sendMessage($(".J-im-btn-sendlink").attr("produrl"));
    },
    _sendMessage:function(sendMsg){
		if(!sendMsg){
			return;
		}
        var that = this;
        //和历史数据对比，增加时间戳
        var newTime = new Date();
        that.views.ChatContentView.addTimestamp(that.lastMsgTime,newTime);

        //发送
        sendMsg = chatImgUtil.title2code(sendMsg);
        var msgId = that.api.sdk.sendMessage(that.uid, sendMsg, function success(id, msg){
            that.views.ChatContentView.collection.remove(newMsg.cid);
            that.views.ChatContentView.addMessage(msg);
            that.api.reloadLocalContacts();
        }, function fail(id){
            //$("div[msgcid='"+newMsg.cid+"']").html("<div class='im-icon-resend J-im-msg-resend'></div>");
            $("div[msgcid='"+newMsg.cid+"'] + .J-im-inner").prepend('<i class="im-icon-resend-before J-im-msg-resend"></i>');
        });
        //设置新的历史消息时间值
        that.lastMsgTime = newTime.getTime();
        //将发送数据显示到聊天框
        var newMsg =new Message({id:msgId,msg:sendMsg,userId:that.api.sdk.userId,read:true});
        that.views.ChatContentView.addMessage(newMsg);
        //$("div[msgcid='"+newMsg.cid+"']").html("<div class='im-icon-sending J-im-msg-resend'></div>");
        $("div[msgcid='"+newMsg.cid+"'] + .J-im-inner").prepend('<i class="im-icon-sending-before im-anim-round"></i>');
    }

});

